<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="true" default-expand-all :data="depts" :props="defaultProps">
        <template v-slot="{ data }">
          <el-row type="flex" justify="space-between" align="middle" style="width:100%;height:40px">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <div>
                <el-dropdown @command="operateDept($event, data.id)">
                  <!-- 显示区域内容 -->
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <!-- 下拉菜单选项 -->
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <add_dept
    ref="addDept"
    :is-edit="isEdit"
    :current-node-id="currentNodeId" :show-dialog.sync="showDialog"
    @updateDepartment="loadDepartment"></add_dept>
  </div>
</template>
<script>
import add_dept from './components/add_dept.vue'
import { getDepartment, delDepartment } from '@/api/department'
import { arr2tree } from '@/utils/index'
export default {
  name: 'Department',
  components: { add_dept }, 
  data() {
    return {
      isEdit: false,
      currentNodeId: null, // 存储当前点击的id
      showDialog: false,
      depts: [{
        name: '传智教育',
        children: [
          { name: '总裁办'},
          { name: '行政部'},
          { name: '财务部'}
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.loadDepartment()
  },
  methods:{
    async loadDepartment(){
      const res = await getDepartment()
      const result = arr2tree(res, 0)
      console.log(result)
      this.depts = result 
    },
    operateDept(type, id){
      console.log(type)
      this.isEdit = type === 'edit'

      if(type === 'add' || type === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
      } 
      if(type === 'edit') {
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      }
      if(type === 'del') {
        // 删除部门
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await delDepartment(id)
          // 提示消息
          this.$message.success('删除部门成功')
          this.loadDepartment()
        })
      }
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
